<?php
/**
 * 根据mysql数据库 自动生成model
 */

// ------------------------配置 start------------------------
// $db_host     = '127.0.0.1'; // host
// $db_port     = '3306'; // 端口
// $db_username = 'root'; // 账号
// $db_password = 'root'; // 密码
// $db_database = 'xinrui'; // 数据库名
// $db_prefix   = 'web_'; // 表前缀

// $output_dir = __DIR__ . '/models'; // 输出文件夹
// ------------------------配置 end------------------------

// ------------------------ 配置 start ------------------------
$file = __DIR__ . '/../../.env';
$env  = parse_ini_file($file , true);
print_r($env);

$db_host     = $env['DATABASE']['HOSTNAME'] ?? '127.0.0.1'; // host
$db_port     = $env['DATABASE']['HOSTPORT'] ?? '3306'; // 端口
$db_username = $env['DATABASE']['USERNAME'] ?? 'root'; // 账号
$db_password = $env['DATABASE']['PASSWORD'] ?? 'root'; // 密码
$db_database = $env['DATABASE']['DATABASE'] ?? 'zcm_php'; // 数据库名
$db_prefix   = $env['DATABASE']['PREFIX'] ?? 'zcm_'; // 表前缀

$model_dir = __DIR__ . '/../../app/common/model';
$dao_dir = __DIR__ . '/../../app/common/dao';

// ------------------------ 配置 end ------------------------

function strToHump($str)
{
    $str = ucwords(str_replace('_', ' ', $str));
    $str = str_replace(' ', '', lcfirst($str));
    return ucfirst($str);
}

// 表
$tables = [];

// 创建文件夹
if (!is_dir($model_dir)) {
    mkdir($model_dir, 0777, 1);
}
if (!is_dir($dao_dir)) {
    mkdir($dao_dir, 0777, 1);
}

// 连接数据库
$mysql_conn = @mysqli_connect($db_host, $db_username, $db_password, $db_database, $db_port) or die("Mysql connect is error.");
mysqli_query($mysql_conn, 'SET NAMES utf8');

// 是否指定表名
if ($argc >= 2) {
    // 指定表名
    $table_name = $argv;
    unset($table_name[0]); // 第一个参数为文件名
    foreach ($table_name as $value) {
        $tables[]['TABLE_NAME'] = $value;
    }
} else {
    // 取得所有的表名
    $table_result = mysqli_query($mysql_conn, 'show tables');
    while ($row = mysqli_fetch_array($table_result)) {
        $tables[]['TABLE_NAME'] = $row[0];
    }
}

// 循环取得所有表的备注及表中列消息
foreach ($tables as $k => $v) {
    $sql  = "SELECT * FROM ";
    $sql .= "INFORMATION_SCHEMA.TABLES ";
    $sql .= "WHERE ";
    $sql .= "table_name = '{$v['TABLE_NAME']}' AND table_schema = '{$db_database}'";
    $table_result = mysqli_query($mysql_conn, $sql);
    while ($t = mysqli_fetch_assoc($table_result)) {
        $tables[$k]['TABLE_CN_NAME'] = $t['TABLE_COMMENT'];
        $tables[$k]['TABLE_COMMENT'] = $t['TABLE_COMMENT'];
    }

    $sql  = "SELECT * FROM ";
    $sql .= "INFORMATION_SCHEMA.COLUMNS ";
    $sql .= "WHERE ";
    $sql .= "table_name = '{$v['TABLE_NAME']}' AND table_schema = '{$db_database}'";
    $field_result = mysqli_query($mysql_conn, $sql);
    $fields       = array();
    while ($t = mysqli_fetch_assoc($field_result)) {
        $fields[] = $t;
    }
    $tables[$k]['COLUMN'] = $fields;
}

$existCount = 0;
// 循环所有表
foreach ($tables as $k => $v) {
    // 模板参数定义
    $table_name = substr($v['TABLE_NAME'], strlen($db_prefix));
    $table_desc = $v['TABLE_COMMENT'];
    $class_name = strToHump($table_name);

    // 循环所有字段
    $class_propertys_doc_str = '';
    $class_myschema_doc_str  = '';
    $class_methods_doc_str   = '';
    foreach ($v['COLUMN'] as $f) {
        $colName = $f['COLUMN_NAME'];
        $comment = $f['COLUMN_COMMENT'];

        $default = '';
        if (isset($f['COLUMN_DEFAULT']) && strlen($f['COLUMN_DEFAULT']) > 0) {
            if ($f['COLUMN_DEFAULT'] == 'NULL') {
                $f['COLUMN_DEFAULT'] = 'null';
            } else if ($f['COLUMN_DEFAULT'] == 'current_timestamp()') {
                $f['COLUMN_DEFAULT'] = 'time()';
            }
            $default = '= ' . $f['COLUMN_DEFAULT'];
        }

        $type = 'string';
        if (strpos($f['COLUMN_TYPE'], 'int') !== false) {
            $type = 'int';
        }
        if (strpos($f['COLUMN_TYPE'], 'decimal') !== false
            || strpos($f['COLUMN_TYPE'], 'numeric') !== false
        ) {
            $type = 'float';
        }

        switch ($colName)
        {
            case "id":
                $comment = "ID";
                break;  
            case "create_time":
                $comment = "创建时间";
                break;
            case "update_time":
                $comment = "修改时间";
                break;
        }

        // 'min_number'    => 'int', // 最小值
        $class_propertys_doc_str .= "        '" . $colName . "' => '" . $type . "', // " . $comment . PHP_EOL;

        // 自定义数据表架构
        $new_default = str_replace("= ", "", $default);
        $class_myschema_doc_str .= "        '" . $colName . "' => ['comment' => '" . $comment . "', 'type' => '" . $type . "', 'column_type' => '" . $f['COLUMN_TYPE'] . "', 'default' => '" . $new_default . "']," . PHP_EOL;

        // 注释
        $class_methods_doc_str .= " * @var {$type} {$colName} {$comment}" . PHP_EOL;
    }

    // 遍历每张表
    // 得到结果并导出
    $data = [
        'db_prefix'               => $db_prefix,
        'class_name'              => $class_name,
        'class_propertys_doc_str' => rtrim($class_propertys_doc_str),
        'class_myschema_doc_str'  => rtrim($class_myschema_doc_str),
        'class_methods_doc_str'   => rtrim($class_methods_doc_str),
        'table_name'              => $table_name,
        'table_desc'              => $table_desc,
        'date_time'               => date('Y-m-d H:i'),
    ];

    // 生成模形
    $text   = file_get_contents(__DIR__ . "/model_template.temp");
    $result = preg_replace_callback("#\{(.*?)\}#", function ($t) use ($data) {
        if (!empty($data[$t[1]])) {
            return $data[$t[1]];
        } else {
            return '';
        }
    }, $text);
    
    $modelPath = $model_dir . "/{$class_name}Model.php";
    file_put_contents($modelPath, $result);
    @chmod($modelPath, 0777);

    // 生成服务（已存在即跳过）
    $text2   = file_get_contents(__DIR__ . "/dao_template.temp");
    $result2 = preg_replace_callback("#\{(.*?)\}#", function ($t) use ($data) {
        if (!empty($data[$t[1]])) {
            return $data[$t[1]];
        } else {
            return '';
        }
    }, $text2);

    $daoPath = $dao_dir . "/{$class_name}Dao.php";
    if (!is_file($daoPath)) {
        file_put_contents($daoPath, $result2);
        @chmod($daoPath, 0777);
    }

    echo 'success: ' . $modelPath . PHP_EOL;


}
mysqli_close($mysql_conn);

echo 'output finish! skip:' . $existCount . ' (because is exists)';
